package com.powerunion.datacollection.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.PendingTaskDao;
import com.powerunion.datacollection.model.jsonObject.Item;
import com.powerunion.datacollection.model.jsonObject.TaskInfo;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.util.log.LogHelper;

public class PendingTaskDaoImpl extends JdbcBase implements PendingTaskDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			PendingTaskDaoImpl.class);

	/**
	 * 查找该用户当前的待办任务
	 * 
	 * @param userCode
	 * @return
	 */
	public List findPendingTaskByUser(String userCode) throws DaoException {
		StringBuffer sql = new StringBuffer();
		
		sql.append("select a.id,a.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,a.act_id,a.staff_id,a.date_approve time_limit, ")
		   .append(" a.form_id,a.aw_state state,a.iupdata iupdata,(select act_name from dc_proc_instance where id =a.pre_act_id )")
		   .append("actName,a.work_type,a.create_date,b.full_name  from dc_item_info t left join dc_approve_work a on a.proc_id = t.id left join dc_wf_instance w ")
		   .append(" on t.id = w.proc_id left join base_user b on b.user_code = a.staff_id where a.staff_id = ? and a.aw_state <>  5 and a.aw_state <> 4  and a.aw_state <> 6 ")
		   .append(" and a.aw_state <> 2 and a.aw_state <> 8 and a.aw_state <> 9  ")
		   .append(" UNION ")
		   .append(" select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,s.act_id,s.staff_id,s.time_limit,s.form_id,")
		   .append(" s.sw_state state,s.sw_type iupdata,s.sw_name actName,s.work_type,s.create_date,b.full_name from dc_item_info t  ")
		   .append(" left join dc_submission_work s on s.proc_id = t.id left join dc_wf_instance w on t.id = w.proc_id  left join base_user b on ")
		   .append(" b.user_code = s.staff_id where s.staff_id = ? and s.sw_state <> 5")
		   .append(" and  s.sw_state <> 6 and  s.sw_state <> 4 and  s.sw_state <> 2 and  s.sw_state <> 8 and s.sw_type <> 8 ");

		List pendingTaskList = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

		try {
			pendingTaskList = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					TaskInfo swi = new TaskInfo();
					swi.setId(rs.getFieldValueAsString("id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));
					swi.setProcName(rs.getFieldValueAsString("item_name"));
					swi.setTaskDesc(rs
							.getFieldValueAsString("wf_instance_desc"));
					swi.setTaskName(rs.getFieldValueAsString("wf_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi.setType(rs.getFieldValueAsInteger("work_type").intValue());
					swi.setIupdata(rs.getFieldValueAsInteger("iupdata") == null ? 0
							: rs.getFieldValueAsInteger("iupdata")
							.intValue());
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
					swi.setTimeLimitStr(rs.getFieldValueAsString("time_limit"));
					swi.setFormId(rs.getFieldValueAsString("form_id"));
					swi.setState(rs.getFieldValueAsInteger("state")
							.intValue());
					swi.setPreActName(rs.getFieldValueAsString("actName"));
					String createDateStr = Format.getInstance().dateToString(rs.getFieldValueAsDate("create_date"));
					swi.setCreateDate(createDateStr);

					swi.setStatffName(rs.getFieldValueAsString("full_name"));

					pendingTaskList.add(swi);

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("查找用户编码为：" + userCode + "的当前待办任务失败！", e);
			throw new DaoException("查找用户编码为：" + userCode + "的当前待办任务失败！");
		}

		return pendingTaskList;
	}
	
	public List findPendingTask4WebService(String userCode) throws DaoException {
		StringBuffer sql = new StringBuffer();
		
		sql.append("select a.id,a.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,a.act_id,a.staff_id,a.date_approve time_limit, ")
		   .append(" a.form_id,a.aw_state state,a.iupdata iupdata,(select act_name from dc_proc_instance where id =a.pre_act_id )")
		   .append("actName,a.work_type,a.create_date,b.full_name  from dc_item_info t left join dc_approve_work a on a.proc_id = t.id left join dc_wf_instance w ")
		   .append(" on t.id = w.proc_id left join base_user b on b.user_code = a.staff_id where a.staff_id = ? and a.aw_state <>  5 and a.aw_state <> 4  and a.aw_state <> 6 ")
		   .append(" and a.aw_state <> 2 and a.aw_state <> 8 and a.aw_state <> 9  ")
		   .append(" UNION ")
		   .append(" select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,s.act_id,s.staff_id,s.time_limit,s.form_id,")
		   .append(" s.sw_state state,s.sw_type iupdata,s.sw_name actName,s.work_type,s.create_date,b.full_name from dc_item_info t  ")
		   .append(" left join dc_submission_work s on s.proc_id = t.id left join dc_wf_instance w on t.id = w.proc_id  left join base_user b on ")
		   .append(" b.user_code = s.staff_id where s.staff_id = ? and s.sw_state <> 5")
		   .append(" and  s.sw_state <> 6 and  s.sw_state <> 4 and  s.sw_state <> 2 and  s.sw_state <> 8 and s.sw_type <> 8 ");

		List items = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

		try {
			items = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					Item item = new Item();
					String createDateStr = Format.getInstance().dateToString(rs.getFieldValueAsDate("create_date"));
					item.setArriveTime(createDateStr);
					item.setCreationDepartment(rs.getFieldValueAsString("actName"));
					item.setCreationDepartmentID("");
					item.setCreator(rs.getFieldValueAsString("actName"));
					item.setCreatorId("");
					item.setExecutor(rs.getFieldValueAsString("full_name"));
					item.setExecutorID(rs.getFieldValueAsString("staff_id"));
					item.setTitle(rs.getFieldValueAsString("wf_name"));
					
					String formId = rs.getFieldValueAsString("form_id");
					String procId = rs.getFieldValueAsString("proc_id");
					String id = rs.getFieldValueAsString("id");
					String actId = rs.getFieldValueAsString("act_id");
					
					StringBuffer url = new StringBuffer();
					int state = rs.getFieldValueAsInteger("state")==null?0:rs.getFieldValueAsInteger("state").intValue();
					int workType = rs.getFieldValueAsInteger("work_type").intValue();
					if(workType == Constants.TASK_TYPE_SUBMISSIONWORK){//采集任务
						if(state == Constants.SUBMISSION_WAIT){
							url.append("/DataCollection/dataCollection/collectionForm.do?method=showTemplate")
							   .append("&fsetId=").append(formId).append("&reType=\"subs\"&procId=").append(procId)
							   .append("&actId=").append(actId).append("&swId=").append(id).append("&state=").append(state);
						}else if(state == Constants.SUBMISSION_NOTSUBMIT){
							url.append("/DataCollection/dataCollection/collectionForm.do?method=showTemplate")
							   .append("&fsetId=").append(formId).append("&reType=\"update\"&procId=").append(procId)
							   .append("&actId=").append(actId).append("&swId=").append(id).append("&state=").append(state);
						}else if(state == Constants.SUBMISSION_DISACCORD){
							url.append("/DataCollection/dataCollection/collectionForm.do?method=showTemplate")
							   .append("&fsetId=").append(formId).append("&reType=\"update\"&procId=").append(procId)
							   .append("&actId=").append(actId).append("&swId=").append(id).append("&state=").append(state);
						}
					}else if(workType == Constants.TASK_TYPE_APPROVEWORK) {
						int iupdata = rs.getFieldValueAsInteger("iupdata") == null ? 0
								: rs.getFieldValueAsInteger("iupdata")
								.intValue();
						url.append("/DataCollection/dataCollection/dataCollectView.do?method=dataCollectView")
						   .append("&fsetId=").append(formId).append("&reType=\"actData\"&procId=").append(procId)
						   .append("&actId=").append(actId).append("&approveId=").append(id).append("&awState=").append(state)
						   .append("&iupdata=").append(iupdata);
					}
					
					item.setUrl(url.toString());
					item.setWorkType("");

					items.add(item);

					rs.next();
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("查找用户编码为：" + userCode + "的当前待办任务失败！", e);
			throw new DaoException("查找用户编码为：" + userCode + "的当前待办任务失败！");
		}

		return items;
	}

	public static void main(String[] args){
		PendingTaskDaoImpl ptl = new PendingTaskDaoImpl();
		List t = new ArrayList();
		try {
			t = ptl.findPendingTaskByUser("gp");
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("size:"+t.size());
	}

}
